package leetcode.code0846;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import leetcode.IDebug;
import leetcode.helper.HelpDebug;

/**
 * 执行用时：42 ms, 在所有 Java 提交中击败了67.39%的用户
 *
 * 内存消耗：41.4 MB, 在所有 Java 提交中击败了5.27%的用户
 *
 * 通过测试用例：73 / 73
 */
public class Solution3 implements IDebug {

	public boolean isNStraightHand(int[] hand, int groupSize) {
		int len = hand.length;
		Map<Integer, Integer> map = new HashMap<>();
		Set<Integer> set = new HashSet<>();
		for (int i = 0; i < len; i++) {
			int num = hand[i];
			map.put(num, map.getOrDefault(num, 0) + 1);
			set.add(num);
		}
		int range = set.size();
		if (groupSize - 1 >= range) {
			return false;
		}
		List<Integer> list = new ArrayList<>(set);
		list.sort((a, b) -> a - b);
		int[][] hash = new int[range][2];
		for (int i = 0; i < range; i++) {
			int num = list.get(i);
			hash[i][0] = num;
			hash[i][1] = map.get(num);
		}
		int[] help = new int[range];
		help[0] += -hash[0][1];
		help[groupSize - 1] += hash[0][1];
		int sum = help[0];
		int num = hash[0][0];
		for (int i = 1; i < range; i++) {
			int cur = hash[i][0];// 数字
			int sub = hash[i][1];// 个数
			if (sum != 0 && num + 1 != cur) {
				return false;
			}
			num = cur;
			int diff = sum + sub;
			if (diff != 0) {
				help[i] += -diff;
				if (i + groupSize - 1 >= range) {
					return false;
				}
				help[i + groupSize - 1] += diff;
			}
			sum += help[i];
		}
		return true;
	}

	@Override
	public void debug1() {
		HelpDebug.compare(true, this.isNStraightHand(HelpDebug.str2array3("[5,1]"), 1));

	}

	public void debug5() {
		HelpDebug.compare(false, this.isNStraightHand(HelpDebug.str2array3("[1,1,2,2,3,3]"), 4));

	}

	@Override
	public void debug2() {
		HelpDebug.compare(false, this.isNStraightHand(HelpDebug.str2array3("[1,2,3,4,5]"), 4));

	}

	@Override
	public void debug3() {
		HelpDebug.compare(false, this.isNStraightHand(HelpDebug.str2array3(
				"[233722108,386144634,221638886,175028874,408337082,91410299,793763682,972910825,627251147,135020779]"),
				2));

	}

	@Override
	public void debug4() {
		HelpDebug.compare(true, this.isNStraightHand(HelpDebug.str2array3("[1,2,3,6,2,3,4,7,8]"), 3));

	}

	public static void main(String[] args) {
		Solution3 so = new Solution3();
		so.debug5();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
